package com.socket.UDP.server;

import com.socket.UDP.Thread.UDPThread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by wangyg on 2016/10/31.
 */
public class UDPServer {
	public static void main(String[] args) throws IOException {
				//创建服务器端DatagramSocket，指点端口
	/*			DatagramSocket socket = new DatagramSocket(8989);
				//创建数据报，用于接收客户端发送的数据
				byte[] data = new byte[1024];
				DatagramPacket packet = new DatagramPacket(data, data.length);
				System.out.println("服务器端已启动，等待连接。。。");
				//接收客户端发送的数据
				socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
				//读取数据
				String info = new String(data, 0, packet.getLength());
				System.out.println("服务器接收成功，消息为：" + info);

				//响应请求
				InetAddress address = packet.getAddress();
				int port = packet.getPort();
				byte[] sendData = "欢迎你的到来.".getBytes();
				DatagramPacket packet1 = new DatagramPacket(sendData, sendData.length, address, port);
				//发送信息
				socket.send(packet1);
				//关闭连接
				socket.close();*/

//		支持多用户的UDP协议
		DatagramSocket socket = new DatagramSocket(8989);
		//穿件数据报，用于接收客户端发送的数据

		System.out.println("服务器端已启动，等待连接。。。");
		int count=0;
		while (true) {
			byte[] data = new byte[1024];
			DatagramPacket packet = new DatagramPacket(data, data.length);
			socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
			UDPThread thread = new UDPThread(socket,packet,data);
			count++;
			thread.start();
			System.out.println("当前线程名称为"+thread.getName());
			System.out.println("当前连接数量为"+count);
		}

	}
}
